
package it.csttech.date;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.ws.rs.WebApplicationException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * This class is a module of the object mapper whose purpose is to marshal a
 * java date object into a JSON string according to the request locale
 * 
 * @author marcello.felappi
 * @author marco.dalena
 */

public class DateJsonSerializer extends JsonSerializer<Date> {

	/**
	 * Locale of the request.
	 */
	private Locale locale;

	/**
	 * Empty constructor, needed by the framework to build the date serializer
	 * in the correct way.
	 */
	public DateJsonSerializer() {

	}

	/**
	 * Constructor, accepts a locale in input and builds the date serializer.
	 */
	public DateJsonSerializer(Locale locale) {

		this.locale = locale;
	}

	public Locale getLocale() {

		return locale;
	}

	public void setLocale(Locale locale) {

		this.locale = locale;
	}

	/**
	 * Method that perform serialization; accept a date, a json generator and a
	 * serialize provider. The method read the locale and create a DateFormat
	 * coherent with it. If the locale is not supported, the method throws an
	 * exception.
	 * 
	 * @param Date
	 *            - input date to be serialized
	 * @param JsonGenerator
	 *            - generator used for serializing a json file
	 * @param SerializerProvider
	 *            - provider in which the date serializer will be registered
	 * @throws IOException
	 *             - thrown if I/O error occurs
	 * @throws JsonProcessingException
	 *             - thrown if an error during json processing occurs
	 * @throws WebApplicationException
	 *             - thrown if the locale of the client is not supported
	 */
	@Override
	public void serialize(Date date, JsonGenerator jgen, SerializerProvider sp)
		throws IOException, JsonProcessingException {

		DateFormat dFormat = null;
		try {
			dFormat =
				DateFormat.getDateInstance(SimpleDateFormat.SHORT, locale);
		}
		catch (Exception e) {
			throw new WebApplicationException(
				Messages.getString("ErrorCode.localeNotSupported"));
		}
		jgen.writeString(dFormat.format(date));

	}

}
